package stores

import (
	"context"

	"github.com/google/uuid"
)

type UserSession struct {
	Token      string
	OpenId     string
	UnionId    string
	Data       string
	SessionKey string
}

func (u *UserSession) SetOpenId(openid string) {
	if openid != "" {
		u.OpenId = openid
	}
}

func (u *UserSession) SetUnionId(unionid string) {
	if unionid != "" {
		u.UnionId = unionid
	}
}

func (u *UserSession) SetData(data string) {
	if data != "" {
		u.Data = data
	}
}

func (u *UserSession) SetSessionKey(sessionKey string) {
	if sessionKey != "" {
		u.SessionKey = sessionKey
	}
}

// GenToken 这里用户token仅用uuid做演示，需要用户自行结合自己的应用覆盖实现
func GenToken(context context.Context) string {
	return uuid.New().String()
}

// 缓存实现需要开发者自行覆盖
var memCache = make(map[string]UserSession)

func SetCache(context context.Context, token string, openid string, unionid string, data string, sessionKey string) string {
	cacheData, exist := memCache[token]
	if !exist {
		cacheData = UserSession{}
		cacheData.SetData(data)
		cacheData.SetOpenId(openid)
		cacheData.SetUnionId(unionid)
		cacheData.SetSessionKey(sessionKey)
		newToken := GenToken(context)
		memCache[newToken] = cacheData
		return newToken
	} else {
		cacheData.SetData(data)
		cacheData.SetOpenId(openid)
		cacheData.SetUnionId(unionid)
		cacheData.SetSessionKey(sessionKey)
		memCache[token] = cacheData
		return token
	}
}

func GetCache(context context.Context, token string) (UserSession, bool) {
	data, exist := memCache[token]
	return data, exist
}
